/**
 * @author banglong
 * @date 2016/10/8
 */
define(['avalon', 'Layer', 'tools', 'stockSearchApi', 'getVmConfig', 'chooseCondition', 'GoodsSelectDialog',
    'text!../html/index/report/stockSearchTemp.html!strip', 'conditionsUtils', 'rootPath'
  ],
  function (avalon, layer, tools, api, getVmConfig, chooseCondition, GoodsSelectDialog, htmlTemp, conditionsUtils, rootPath) {

    var showMenu; // 显示菜单方法
    var checkBreadcrumb; // 检查路径错误
    var Openparm; // 参数
    var currentDept;
    var providerDept;
    var excelParam;

    var stockSearchVm;
    var getVmOption = function () {
      return {
        $id: 'stockSearch',
        breadcrumb: '', //路径
        isProviderDept: false,

        columnNames: [], // 表格列名
        columnValueNames: [], // 表格值

        showCounts: false,
        counts: 0,
        searchValue: '',

        accountName: '',
        accountID: '',
        booksName: '',
        booksID: '',

        goodsBigCatName: '',
        goodsBigCatID: '',
        goodsMidCatName: '',
        goodsMidCatID: '',
        goodsSmallCatName: '',
        goodsSmallCatID: '',

        goodName: '',
        goodID: '',
        goods: [],
        size: 30, // 大小
        pages: 0, // 页数
        count: 0, // 总数

        back: function () {
          var main = document.querySelector('#main');
          main.removeChild(tools.getFirstElementChild(main));
          checkBreadcrumb();
          showMenu();
        },

        chooseCondition: function (e, type) {
          var theEvent = e || window.event;
          var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
          if (code !== 13) {
            return;
          }

          var param = {
            type: type
          };
          switch (type) {
            case 0:
              param.chooseConditionsFunc = function (condition) {
                stockSearchVm.accountName = condition.DeptAccountName;
                stockSearchVm.accountID = condition.DeptAccountID;
              };
              param.searchValue = stockSearchVm.accountName;
              break;
            case 1:
              param.chooseConditionsFunc = function (condition) {
                stockSearchVm.booksName = condition.GoodsBookName;
                stockSearchVm.booksID = condition.GoodsBookID;
              };
              param.searchValue = stockSearchVm.booksName;
              break;
            case 2:
              param.chooseConditionsFunc = function (condition) {
                stockSearchVm.goodsBigCatName = condition.GoodsBigCatName;
                stockSearchVm.goodsBigCatID = condition.GoodsBigCatID;
              };
              param.GoodsBookID = stockSearchVm.booksID;
              param.searchValue = stockSearchVm.goodsBigCatName;
              break;
            case 3:
              param.chooseConditionsFunc = function (condition) {
                stockSearchVm.goodsMidCatName = condition.GoodsMidCatName;
                stockSearchVm.goodsMidCatID = condition.GoodsMidCatID;
              };
              param.GoodsBigCatID = stockSearchVm.goodsBigCatID;
              param.searchValue = stockSearchVm.goodsMidCatName;
              break;
            case 4:
              param.chooseConditionsFunc = function (condition) {
                stockSearchVm.goodsSmallCatName = condition.GoodsSmallCatName;
                stockSearchVm.goodsSmallCatID = condition.GoodsSmallCatID;
              };
              param.GoodsMidCatID = stockSearchVm.goodsMidCatID;
              param.searchValue = stockSearchVm.goodsSmallCatName;
              break;
          }
          chooseCondition.init(param);
        },

        chooseGoods: function (e) {
          var theEvent = e || window.event;
          var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
          if (code !== 13) {
            return;
          }

          new GoodsSelectDialog().init({
            Openparm: Openparm,
            isGYKS: false,
            CurrentDeptAccount: currentDept,
            ProviderDeptAccount: providerDept,
            searchValue: stockSearchVm.goodName, //初始的查询信息
            getAll: true,
            condition: conditionsUtils.getGoodsCondition({
              GoodsBookID: stockSearchVm.booksID
            }),
            GoodsBookID: stockSearchVm.booksID,
            pushChooseGoods: function (data) { // 选择物品
              stockSearchVm.goodName = data.GoodsName;
              stockSearchVm.goodID = data.GoodsID;
            }
          });
        },

        search: function () {
          var goodsSmallCatID = stockSearchVm.goodsSmallCatID || '%';
          var goodsMidCatID = stockSearchVm.goodsMidCatID || '%';
          var deptAccountID = stockSearchVm.accountID || '%';
          var goodsID = stockSearchVm.goodID || '%';
          var goodsBookID = stockSearchVm.booksID || '%';
          var goodsBigCatID = stockSearchVm.goodsBigCatID || '%';

          var loadIndex = layer.load();
          excelParam = {
            className: 'StoreBatchManager',
            method: 'GetDeptBookStore',
            goodsSmallCatID: goodsSmallCatID,
            goodsMidCatID: goodsMidCatID,
            deptAccountID: deptAccountID,
            goodsID: goodsID,
            goodsBookID: goodsBookID,
            goodsBigCatID: goodsBigCatID
          };

          var page = document.querySelector('#stockSearchPage');
          page.innerHTML = '';
          api.getDeptBookStore(excelParam).then(function (jsonResult) {

            if (jsonResult.issuccess !== 0) {
              return Promise.reject("查询科室实时库存失败");
            }

            var result = JSON.parse(jsonResult.result);
            stockSearchVm.showCounts = true;
            stockSearchVm.counts = result.length;
            tools.initPage(page, stockSearchVm.size, stockSearchVm, stockSearchVm.goods, result);
            layer.close(loadIndex);

          })['catch'](function (ex) {
            layer.close(loadIndex);
            tools.handleError(ex);
          });
        },

        excelExport: function () {
          if (stockSearchVm.goods.length <= 0 || !excelParam) {
            tools.handleError("请确认查询结果不为空");
            return;
          }
          // 导出excel
          var url = rootPath.getRootPath() + "export/stockExcel";
          if (tools.isIEByActiveObject()) {
            tools.DownLoadFile({
              url: url.split('?')[0],
              data: {
                name: '科室实时库存',
                className: excelParam.className,
                method: excelParam.method,
                goodsSmallCatID: encodeURIComponent(excelParam.goodsSmallCatID),
                goodsMidCatID: encodeURIComponent(excelParam.goodsMidCatID),
                deptAccountID: encodeURIComponent(excelParam.deptAccountID),
                goodsID: encodeURIComponent(excelParam.goodsID),
                goodsBookID: encodeURIComponent(excelParam.goodsBookID),
                goodsBigCatID: encodeURIComponent(excelParam.goodsBigCatID),
                fieldName: stockSearchVm.columnNames.$model.join(','),
                fieldValueName: stockSearchVm.columnValueNames.$model.join(',')
              }
            });
          } else {
            url += '?name=' + encodeURIComponent(encodeURIComponent('科室实时库存'));
            url += '&className=' + encodeURIComponent(encodeURIComponent(excelParam.className));
            url += '&method=' + encodeURIComponent(encodeURIComponent(excelParam.method));
            url += '&goodsSmallCatID=' + encodeURIComponent(encodeURIComponent(excelParam.goodsSmallCatID));
            url += '&goodsMidCatID=' + encodeURIComponent(encodeURIComponent(excelParam.goodsMidCatID));
            url += '&deptAccountID=' + encodeURIComponent(encodeURIComponent(excelParam.deptAccountID));
            url += '&goodsID=' + encodeURIComponent(encodeURIComponent(excelParam.goodsID));
            url += '&goodsBookID=' + encodeURIComponent(encodeURIComponent(excelParam.goodsBookID));
            url += '&goodsBigCatID=' + encodeURIComponent(encodeURIComponent(excelParam.goodsBigCatID));
            url += '&fieldName=' + encodeURIComponent(encodeURIComponent(JSON.parse(JSON.stringify(stockSearchVm.columnNames.$model)).join(',')));
            url += '&fieldValueName=' + encodeURIComponent(encodeURIComponent(JSON.parse(JSON.stringify(stockSearchVm.columnValueNames.$model)).join(',')));
            window.location.href = url;
          }
        },

        showValue: function (el, key) {
          if (typeof el[key] === "boolean") {
            return el[key] ? '是' : '否';
          } else {
            return el[key];
          }
        },

        showClass: function (el, key) {
          if (typeof el[key] === "boolean") {
            return el[key] ? 'blue' : 'red';
          } else {
            return '';
          }
        }
      };
    };

    // 登录科室详细信息
    function getCurrentDeptInfo() {
      currentDept = JSON.parse(localStorage.getItem('deptInfo'));
      api.getOutDTODept({
        className: 'DeptAccountManager',
        method: 'GetDepAccountByAccountID',
        deptAccountID: currentDept.DeptAccountID
      }).then(function (jsonResult) {

        if (jsonResult.issuccess !== 0) {
          return Promise.reject('获取科室部门信息失败');
        }

        currentDept = Object.assign({}, currentDept, JSON.parse(jsonResult.result));
        stockSearchVm.accountName = currentDept.DeptAccountName;
        stockSearchVm.accountID = currentDept.DeptAccountID;
        localStorage.removeItem('deptInfo');
        localStorage.setItem('deptInfo', JSON.stringify(currentDept));

      })['catch'](function (ex) {
        tools.handleError(ex);
      });
    }

    // 供应科室 详细信息
    function getProviderDeptInfo() {
      api.getOutDTODept({
        className: 'OrganizationManager',
        method: 'GetOutDTODept',
        ksdm: Openparm.ProviderDept
      }).then(function (jsonResult) {

        if (jsonResult.issuccess !== 0) {
          return Promise.reject('获取信息失败');
        }
        providerDept = JSON.parse(jsonResult.result);

      })['catch'](function (ex) {
        tools.handleError(ex)
      });
    }

    // 设置 watch 方法监听账册 大类 中类 小类的改变
    function watch(stockSearchVm) {
      stockSearchVm.$watch('accountName', function (value) {
        if (!value) {
          stockSearchVm.accountID = '';
        }
      });
      stockSearchVm.$watch('booksName', function (value) {
        if (!value) {
          stockSearchVm.booksID = '';
          stockSearchVm.goodsBigCatName = '';
          stockSearchVm.goodsMidCatName = '';
          stockSearchVm.goodsSmallCatName = '';
        }
      });
      stockSearchVm.$watch('goodsBigCatName', function (value) {
        if (!value) {
          stockSearchVm.goodsBigCatID = '';
          stockSearchVm.goodsMidCatName = '';
          stockSearchVm.goodsSmallCatName = '';
        }
      });
      stockSearchVm.$watch('goodsMidCatName', function (value) {
        if (!value) {
          stockSearchVm.goodsMidCatID = '';
          stockSearchVm.goodsSmallCatName = '';
        }
      });
      stockSearchVm.$watch('goodsSmallCatName', function (value) {
        if (!value) {
          stockSearchVm.goodsSmallCatID = '';
        }
      });
      stockSearchVm.$watch('goodName', function (value) {
        if (!value) {
          stockSearchVm.goodID = '';
        }
      });
    }

    var init = function ($main, param) {
      $main.append(htmlTemp);
      stockSearchVm = tools.initAvalonVm(avalon, getVmOption(), ".stock-search");
      showMenu = param.showMenu;
      checkBreadcrumb = param.checkBreadcrumb;

      Openparm = param.Openparm; // 初始化参数
      stockSearchVm.breadcrumb = param.breadcrumb;
      stockSearchVm.columnNames.pushArray(getVmConfig.getStockSearchColumnNames()); // 获取表格列名
      stockSearchVm.columnValueNames.pushArray(getVmConfig.getStockSearchColumnValueNames()); // 获取表格列名

      getCurrentDeptInfo();
      getProviderDeptInfo();

      // 设置 watch 方法监听账册 大类 中类 小类的改变
      watch(stockSearchVm);
    };

    return {
      init: init
    }
  });